package com.jiujichaoshi.oauth.server;

import com.jiujichaoshi.oauth.server.security.sms.InMemorySmsCaptchaFindServiceImpl;
import com.jiujichaoshi.oauth.server.security.sms.SmsCaptchaFindService;
import com.jiujichaoshi.oauth.server.security.verify.VerifyHandlerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;

/**
 * 认证服务器入口程序
 *
 * @author YangLong
 */
@SpringBootApplication
public class OauthServerApplication implements WebMvcConfigurer {
    @Autowired
    private Filter ddosDefenderFilter;
    @Autowired
    private VerifyHandlerInterceptor verifyHandlerInterceptor;

    public static void main(String[] args) {
        SpringApplication.run(OauthServerApplication.class, args);
    }

    @Bean
    public SmsCaptchaFindService smsCaptchaFindService() {
        return new InMemorySmsCaptchaFindServiceImpl();
    }

    /**
     * 第一个执行的filter，用于黑名单禁入
     *
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(ddosDefenderFilter);
        registrationBean.addUrlPatterns("/*");
        //保证第一个执行
        registrationBean.setOrder(Integer.MIN_VALUE);
        return registrationBean;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(verifyHandlerInterceptor)
                //可以自定义，哪些URL是需要进行人机验证的
                .addPathPatterns("/**")
                //保证在较为前面执行即可
                .order(0);
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}
